﻿using System;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;
using System.Configuration;
using Microsoft.SharePoint.Utilities;

namespace CSP.Receivers
{
    /// <summary>
    /// A Feature Reciever for GlobalConfigFeature
    /// </summary>
    public abstract class ConfigFileFeatureReceiver : SPFeatureReceiver
    {
    //<configuration>
    //   <connectionStrings>
    //       <add name="AspNetDbCSPConnectionString" connectionString="Data Source=DB-CSP;Initial Catalog=AspNetDb_CSP;Trusted_Connection=yes;" />
    //   </connectionStrings>
    //   <system.web>
    //      <membership defaultProvider="CSPFBAMember">
    //          <providers>
    //              <add connectionStringName="AspNetDbCSPConnectionString" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="1" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" name="CSPFBAMember" type="System.Web.Security.SqlMembershipProvider,System.Web,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" />
    //          </providers>
    //      </membership>
    //      <!-- role provider -->
    //      <roleManager enabled="true" defaultProvider="CSPFBARoleMember">
    //          <providers>
    //              <add connectionStringName="AspNetDbCSPConnectionString" applicationName="/" name="CSPFBARoleMember" type="System.Web.Security.SqlRoleProvider,System.Web,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" />
    //          </providers>
    //      </roleManager>
    //      <authentication mode="Forms">
    //          <forms loginUrl="/_layouts/login.aspx" />
    //      </authentication>
    //   </system.web>


    //   <system.serviceModel>
    //   <bindings>
    //      <wsHttpBinding>
    //        <binding name="WSHttpBinding_IMembershipServiceContract" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
    //          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    //          <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
    //          <security mode="None">
    //          </security>
    //        </binding>
    //      </wsHttpBinding>
    //    </bindings>
    //    <client>
    //      <endpoint address="http://app-csp:15001/MembershipServiceClass.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IMembershipServiceContract" contract="CSP.MembershipInterface.IMembershipServiceContract" name="WSHttpBinding_IMembershipServiceContract">
    //        <identity>
    //          <servicePrincipalName value="host/app-csp" />
    //        </identity>
    //      </endpoint>
    //    </client>
    //  </system.serviceModel>


        /// <summary>
        /// Holds the ModificationEntry objects that must be applied as section nodes.
        /// </summary>
        protected abstract ModificationEntry[] GetSectionEntries ();

        /// <summary>
        /// Holds the ModificationEntry objects that must be applied as child nodes.
        /// </summary>
        protected abstract ModificationEntry[] GetChildNodeEntries();

        /// <summary>
        /// Holds the ModificationEntry objects that must be applied as attributes.
        /// </summary>
        protected abstract ModificationEntry[] GetAttributeEntries();


        public override void FeatureInstalled(SPFeatureReceiverProperties properties) { }
        public override void FeatureUninstalling(SPFeatureReceiverProperties properties) { }

        /// <summary>
        /// Handles the Feature Activation.Adds configuration from the web.config. 
        /// </summary>
        /// <param name="properties">SPFeatureReceiverProperties passes in the "context" 
        /// including the web application reference</param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {

            SPWebApplication WebApp = properties.Feature.Parent as SPWebApplication;

            foreach (ModificationEntry entry in GetSectionEntries())
            {
                WebApp.WebConfigModifications.Add(ModificationEntryHelper.CreateModification(entry.Name, entry.XPath, entry.Value, SPWebConfigModification.SPWebConfigModificationType.EnsureSection)
                );
            }

            foreach (ModificationEntry entry in GetChildNodeEntries())
            {
                WebApp.WebConfigModifications.Add(ModificationEntryHelper.CreateModification(entry.Name, entry.XPath, entry.Value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode)
                );
            }

            foreach (ModificationEntry entry in GetAttributeEntries())
            {
                WebApp.WebConfigModifications.Add(ModificationEntryHelper.CreateModification(entry.Name, entry.XPath, entry.Value, SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute)
                );
            }

            WebApp.Update();
            WebApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();

        }



        /// <summary>
        /// Handles the Feature Deactivation.Removes configuration from the web.config. 
        /// </summary>
        /// <param name="properties">SPFeatureReceiverProperties passes in the "context" 
        /// including the web application reference</param>
        /// <remarks>
        ///  SPWebConfigModification does not remove the settings from the extended sites.
        ///  For more information see http://blogs.devhorizon.com/reza/?p=459
        /// </remarks>
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {

            SPWebApplication WebApp = properties.Feature.Parent as SPWebApplication;

            foreach (ModificationEntry entry in GetAttributeEntries())
            {
                WebApp.WebConfigModifications.Remove(ModificationEntryHelper.CreateModification(entry.Name, entry.XPath, entry.Value, SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute)
                );
            }

            foreach (ModificationEntry entry in GetChildNodeEntries())
            {
                WebApp.WebConfigModifications.Remove(ModificationEntryHelper.CreateModification(entry.Name, entry.XPath, entry.Value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode)
                );
            }

        }
    }
}
